package com.example.sunmi_nfc_manager

import android.content.Context
import android.util.Log
import com.sunmi.nfc.INfcListener
import com.sunmi.nfc.Nfc
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import com.sunmi.peripheralsdk.NfcManager

/** SunmiNfcPlugin */
class SunmiNfcPlugin: FlutterPlugin, MethodCallHandler {
  /// The MethodChannel that will the communication between Flutter and native Android
  private lateinit var channel: MethodChannel
  private lateinit var context: Context
  private var nfcListener: INfcListener.Stub? = null
  private var lastNfcList: List<Map<String, Any>> = emptyList()

  override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
    channel = MethodChannel(flutterPluginBinding.binaryMessenger, "sunmi_nfc_manager")
    channel.setMethodCallHandler(this)
    context = flutterPluginBinding.applicationContext
  }

  override fun onMethodCall(call: MethodCall, result: Result) {
    when (call.method) {
      "initialize" -> {
        Log.d("SunmiNfcPlugin", "event:initialize")
        initializeNfc(result)
      }
      "getCurrentNfcList" -> {
        Log.d("SunmiNfcPlugin", "event:getCurrentNfcList")
        getCurrentNfcList(result)
      }
      "switchNfc" -> {
        Log.d("SunmiNfcPlugin", "event:switchNfc")
        val sn = call.argument<String>("sn")
        switchNfc(sn, result)
      }
      "setNfcWaterMarkAlpha" -> {
        Log.d("SunmiNfcPlugin", "event:setNfcWaterMarkAlpha")
        val alpha = call.argument<Int>("alpha")
        setNfcWaterMarkAlpha(alpha, result)
      }
      "unregisterNfcListener" -> {
        Log.d("SunmiNfcPlugin", "event:unregisterNfcListener")
        unregisterNfcListener(result)
      }
      "destroy" -> {
        Log.d("SunmiNfcPlugin", "event:destroy")
        destroy(result)
      }
      else -> {
        result.notImplemented()
      }
    }
  }

  override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
    channel.setMethodCallHandler(null)
  }

  private fun initializeNfc(result: Result) {
    try {
      NfcManager.init(context) { success ->
        Log.d("SunmiNfcPlugin.initializeNfc", "success: $success")
        if (success) {
          // Register NFC listener
          registerNfcListener()
        }
        result.success(success)
      }
    } catch (e: Exception) {
      Log.e("SunmiNfcPlugin.initializeNfc", "error: ${e.message}")
      result.success(false)
    }
  }

  private fun registerNfcListener() {
    try {
      val listener = object : INfcListener.Stub() {
        override fun onNfcListChanged(nfcList: MutableList<Nfc>?) {
          Log.d("SunmiNfcPlugin", "onNfcListChanged: ${nfcList?.size}")
          // Convert NFC list to map for Flutter
          val nfcMapList = nfcList?.map { nfc ->
            mapOf(
              "sn" to (nfc.sn ?: ""),
              "type" to nfc.type,
              "isSelect" to nfc.isSelect,
              "waterMarkAlpha" to nfc.waterMarkAlpha
            )
          } ?: emptyList()
          
          // 缓存 NFC 列表
          lastNfcList = nfcMapList
          Log.d("SunmiNfcPlugin", "NFC list updated, cached ${nfcMapList.size} items")
        }
      }
      nfcListener = listener
      NfcManager.registerNfcListener(listener)
    } catch (e: Exception) {
      Log.e("SunmiNfcPlugin", "registerNfcListener error: ${e.message}")
    }
  }

  private fun getCurrentNfcList(result: Result) {
    result.success(lastNfcList)
    Log.d("SunmiNfcPlugin", "getCurrentNfcList: returning ${lastNfcList.size} NFCs")
  }

  private fun switchNfc(sn: String?, result: Result) {
    try {
      if (sn != null) {
        NfcManager.switchNfc(sn)
        result.success(true)
      } else {
        result.success(false)
      }
    } catch (e: Exception) {
      Log.e("SunmiNfcPlugin", "switchNfc error: ${e.message}")
      result.success(false)
    }
  }

  private fun setNfcWaterMarkAlpha(alpha: Int?, result: Result) {
    try {
      val alphaValue = alpha ?: 100
      if (alphaValue in 0..100) {
        NfcManager.setNfcWaterMarkAlpha(alphaValue)
        result.success(true)
      } else {
        result.success(false)
      }
    } catch (e: Exception) {
      Log.e("SunmiNfcPlugin", "setNfcWaterMarkAlpha error: ${e.message}")
      result.success(false)
    }
  }

  private fun unregisterNfcListener(result: Result) {
    try {
      nfcListener?.let {
        NfcManager.unregisterNfcListener(it)
        nfcListener = null
      }
      result.success(true)
    } catch (e: Exception) {
      Log.e("SunmiNfcPlugin", "unregisterNfcListener error: ${e.message}")
      result.success(false)
    }
  }

  private fun destroy(result: Result) {
    try {
      nfcListener?.let {
        NfcManager.unregisterNfcListener(it)
        nfcListener = null
      }
      NfcManager.destroy(context)
      result.success(true)
    } catch (e: Exception) {
      Log.e("SunmiNfcPlugin", "destroy error: ${e.message}")
      result.success(false)
    }
  }
}
